package io.github.karino2.pngnote;

import android.content.ContentResolver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.util.Pair;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.Toast;

import androidx.activity.result.ActivityResultCallback;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContract;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;

import io.github.karino2.pngnote.book.FastFile;
import io.github.karino2.pngnote.booklist.BookList;
import io.github.karino2.pngnote.book.BookIO;
import io.github.karino2.pngnote.ui.Page;
import io.github.karino2.pngnote.ui.PageGridAdapter;
import io.github.karino2.pngnotemod.R;

public class BookListActivity extends AppCompatActivity {
    private Uri _url;
    private ActivityResultLauncher getRootDirUrl;
    private Bitmap blankBitmap;
    private List<FastFile> files;
    private List<Page> pageList;
    private Pair bookSizeDP$delegate;
    private BookIO bookIO$delegate;

    public BookListActivity() {

    }

    public void onActCreate() {
        ActivityResultLauncher<Uri> var1 = this.registerForActivityResult((ActivityResultContract) (new ActivityResultContracts.OpenDocumentTree()),
                new ActivityResultCallback<Uri>() {
                    @Override
                    public void onActivityResult(Uri o) {
                        getRootDirUrl$lambda$1(BookListActivity.this, (Uri)o);
                    }
                });
        this.getRootDirUrl = var1;
        Bitmap var6 = Bitmap.createBitmap(100, 100, Bitmap.Config.ARGB_8888);
        Bitmap $this$blankBitmap_u24lambda_u243 = var6;
        int var3 = 0;
        $this$blankBitmap_u24lambda_u243.eraseColor(-3355444);
        this.blankBitmap = var6;
        this.files = new ArrayList<FastFile>(); //CollectionsKt.emptyList();
        this.pageList = new ArrayList<Page>();//CollectionsKt.emptyList();
        try {
            DisplayMetrics metrics = new DisplayMetrics();
            getWindowManager().getDefaultDisplay().getMetrics(metrics);
            this.bookSizeDP$delegate = PageGridActivity.displayMetricsTo4GridSize(metrics);
        } catch (Throwable eee) {
            eee.printStackTrace();
        }
        ContentResolver var111 = BookListActivity.this.getContentResolver();
        this.bookIO$delegate = new BookIO(var111);
    }

    private Uri getLastUri() {
        String var1 = BookList.lastUriStr((Context)this);
        Uri var10000;
        if (var1 != null) {
            String it = var1;
            int var4 = 0;
            var10000 = Uri.parse(it);
        } else {
            var10000 = null;
        }

        return var10000;
    }

    private boolean writeLastUri(Uri uri) {
        return BookList.writeLastUriStr(this, uri.toString());
    }

    private void showMessage(String msg) {
        BookList.showMessage(this, msg);
    }

    private void openRootDir(Uri url) {
        this._url = url;
        this.reloadBookList(url);
    }

    public Bitmap getBlankBitmap() {
        return this.blankBitmap;
    }

    private void updateFiles(List<FastFile> newFiles) {
        this.files.clear();
        this.files.addAll(newFiles);

        List<FastFile> $this$map$iv = (List<FastFile>)newFiles;
        List<Page> var11 = this.pageList;
        List<Page> destination$iv$iv = new ArrayList<Page>(
                ($this$map$iv != null && $this$map$iv.size() > 0) ? $this$map$iv.size() : 10);
        Iterator var7 = $this$map$iv.iterator();

        while(var7.hasNext()) {
            Object item$iv$iv = var7.next();
            FastFile file = (FastFile)item$iv$iv;
            Page var13 = new Page(file.getName(), this.blankBitmap, this.blankBitmap);
            destination$iv$iv.add(var13);
        }

        List<Page> var12 = (List<Page>)destination$iv$iv;

        var11.clear();
        var11.addAll(var12);

        this.requestLoadPages();
    }

    private void requestLoadPages() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                for (int idx = 0; idx < files.size(); ++idx) {
                    FastFile onebookdir = files.get(idx);
                    Bitmap xxx = getBookIO().loadThumbnail(onebookdir);
                    final Bitmap thumbnail = xxx != null ? xxx : blankBitmap;
                    final Bitmap bg = getBookIO().loadBgThumbnail(onebookdir);
                    final int idx_ = idx;
                    BookListActivity.this.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            List<Page> result = new ArrayList<Page>();
                            for (int idx2 = 0; idx2 < pageList.size(); ++idx2) {
                                Page page = pageList.get(idx2);
                                if (idx_ == idx2) {
                                    result.add(page.copy(null, thumbnail, bg));
                                } else {
                                    result.add(page);
                                }
                            }
                            pageList.clear();
                            pageList.addAll(result);
                            bookGridAdapter.notifyDataSetChanged();
                        }
                    });
                }
            }
        }).start();
    }

    private void reloadBookList(Uri url) {
        this.updateFiles(this.listFiles(url));
    }

    private List<FastFile> listFiles(Uri url) {
        FastFile rootDir = FastFile.fromTreeUri(this, url);
        if (!rootDir.isDirectory()) {
            throw new RuntimeException("Not directory");
        } else {
            List<FastFile> result = new ArrayList<FastFile>();
            for (FastFile obj : rootDir.listFiles()) {
                if (obj.isDirectory()) {
                    result.add(obj);
                }
            }
            Collections.sort(result, new Comparator<FastFile>() {
                @Override
                public int compare(FastFile item0, FastFile item1) {
                    String name0 = item0.getName();
                    String name1 = item1.getName();
                    if (name0 == null) name0 = "";
                    if (name1 == null) name1 = "";
                    return -name0.compareTo(name1);
                }
            });
            return result;
        }
    }

    private Pair getBookSizeDP() {
        return this.bookSizeDP$delegate;
    }

    private BookIO getBookIO() {
        return this.bookIO$delegate;
    }

    protected void onRestart() {
        super.onRestart();
        if (!((Collection)this.files).isEmpty()) {
            Uri var10001 = this._url;
            this.reloadBookList(var10001);
        }
    }

    private GridView gridview;
    private PageGridAdapter bookGridAdapter;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        onActCreate();

        //FIXME：
        setContentView(R.layout.activity_booklist);
        ActionBar topAppBar = getSupportActionBar();
        topAppBar.setTitle("Book List");
        topAppBar.setIcon(R.mipmap.ic_launcher);
        if (!Config.USE_ACTIONBAR) {
            topAppBar.hide();
        }
        findViewById(R.id.buttonNewBook).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                onNewBook();
            }
        });
        findViewById(R.id.buttonSettings).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                onSettings();
            }
        });

        gridview = (GridView) findViewById(R.id.bookgridview);
        gridview.setSelector(new ColorDrawable(Color.TRANSPARENT));
        gridview.setBackgroundColor(Color.WHITE);
        bookGridAdapter = new PageGridAdapter(this, pageList);
        gridview.setAdapter(bookGridAdapter);
        gridview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                //int bookType = bookInfoList.get(position).getBookType();
                int pageIdx = position;
                Intent intent = new Intent(BookListActivity.this, BookActivity.class);
                intent.setData(((FastFile)files.get(pageIdx)).getUri());
                startActivity(intent);
            }
        });
        try {
            Uri var2 = this.getLastUri();
            if (var2 != null) {
                Uri it = var2;
                this.openRootDir(it);
                return;
            }
        } catch (Exception var6) {
            this.showMessage("Can't open dir. Please re-open.");
        }
        this.getRootDirUrl.launch((Object)null);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.booklist, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.newBook:
                onNewBook();
                break;

            case R.id.settings:
                onSettings();
                break;
        }
        return true;
    }
    private void onNewBook() {
        NewBookPopup(new OnNewBookListener() {
            @Override
            public void onNewBook(String bookName) {
                addNewBook(bookName);
            }
        }, new OnPopDismissListener() {
            @Override
            public void onDismiss() {

            }
        });
    }
    private void onSettings() {
        getRootDirUrl.launch(null);
    }

    private void addNewBook(String newBookName) {
        Uri var3 = this._url;
        if (var3 != null) {
            Uri it = var3;
            FastFile rootDir = FastFile.fromTreeUri(this, it);
            if (rootDir != null) {
                try {
                    rootDir.createDirectory(newBookName);
                    this.openRootDir(this._url);
                } catch (Exception var8) {
                    this.showMessage("Can't create book directory (" + newBookName + ").");
                }
                return;
            }
        }

        if (false) {
            throw new RuntimeException("Can't open dir"); //FIXME:
        } else {
            Toast.makeText(this, "Can't open dir", Toast.LENGTH_SHORT).show();
        }
    }

    //FIXME:
    private static void getRootDirUrl$lambda$1(BookListActivity this$0, Uri uri) {
        if (uri != null) {
            Uri it = uri;
            this$0.getContentResolver().takePersistableUriPermission(it,
                    Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
            this$0.writeLastUri(it);
            this$0.openRootDir(it);
        }
    }


    EditText g_textState = null;
    private void NewBookPopup(OnNewBookListener onNewBook, OnPopDismissListener onDismiss) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setPositiveButton("CREATE", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                if (onDismiss != null) {
                    onDismiss.onDismiss();
                }
                String textState = "";
                if (g_textState != null) {
                    textState = g_textState.getText().toString();
                }
                if (textState != "") {
                    if (onNewBook != null) {
                        onNewBook.onNewBook(textState);
                    }
                }
            }
        });
        builder.setNegativeButton("CANCEL", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                if (onDismiss != null) {
                    onDismiss.onDismiss();
                }
                if (dialogInterface != null) {
                    dialogInterface.dismiss();
                }
            }
        });
        builder.setOnCancelListener(new DialogInterface.OnCancelListener() {
            @Override
            public void onCancel(DialogInterface dialogInterface) {
                if (onDismiss != null) {
                    onDismiss.onDismiss();
                }
                if (dialogInterface != null) {
                    dialogInterface.dismiss();
                }
            }
        });
        builder.setView(R.layout.dialog_loadpages);
        builder.setCancelable(true);
        final AlertDialog dialog = builder.create();
//        dialog.setContentView(R.layout.dialog_loadpages); //don't use this
        dialog.setOnShowListener(new DialogInterface.OnShowListener() {
            @Override
            public void onShow(DialogInterface dialogInterface) {
                g_textState = dialog.findViewById(R.id.textState);
            }
        });
        dialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialogInterface) {
                g_textState = null;
            }
        });
        dialog.show();
    }

    public interface OnNewBookListener {
        void onNewBook(String bookName);
    }

    public interface OnPopDismissListener {
        void onDismiss();
    }
}